package com.lbj.yuanxi.yx001

import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.graphics.PixelFormat
import android.graphics.Point
import android.os.Build
import android.view.Gravity
import android.view.MotionEvent
import android.view.WindowManager
import android.widget.Toast
import kotlin.math.abs

@SuppressLint("ClickableViewAccessibility")
class FloatingWindowManager private constructor(private val mContext: Context) {

    /**
     * 方法1：addView() 向当前的手机窗口界面添加View
     * 方法2：removeView() 从当前窗体上移除View
     * 方法3：updateViewLayout() 刷新当前View的显示
     */
    private var mWindowManager = mContext.getSystemService(Service.WINDOW_SERVICE) as WindowManager

    // 创建小球对象
    private var mCircleView = FloatingWindowView(mContext)

    private val params = WindowManager.LayoutParams()

    companion object {

        @SuppressLint("StaticFieldLeak")
        @Volatile
        private var instance: FloatingWindowManager? = null

        fun getInstance(context: Context): FloatingWindowManager {
            if (instance == null) {
                synchronized(FloatingWindowManager::class.java) {
                    if (instance == null) {
                        instance = FloatingWindowManager(context)
                    }
                }
            }
            return instance!!
        }
    }

    private var startX = 0f
    private var startY = 0f
    private var absX = 0f
    private var absY = 0f

    init {
        mCircleView.setOnTouchListener { _, event ->

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startX = event.rawX
                    startY = event.rawY
                    absX = 0f
                    absY = 0f
                }
                MotionEvent.ACTION_MOVE -> {
                    val moveX = event.rawX
                    val moveY = event.rawY
                    val dx = moveX - startX
                    val dy = moveY - startY
                    params.x += dx.toInt() // 设置X轴偏移量
                    params.y += dy.toInt() // 设置Y轴偏移量
                    mCircleView.setDrawLogo(true)
                    mWindowManager.updateViewLayout(mCircleView, params)
                    startX = moveX
                    startY = moveY
                    absX += abs(dx)
                    absY += abs(dy)
                }
                MotionEvent.ACTION_UP -> {
                    // 判断手指抬起时，让小球靠边
                    val x = event.rawX
                    if (x > getWindowWidth() / 2) {
                        params.x = getWindowWidth() - mCircleView.width
                    } else {
                        params.x = 0
                    }
                    mCircleView.setDrawLogo(false)
                    mWindowManager.updateViewLayout(mCircleView, params)
                    // 解决事件冲突，当滑动距离为0时为点击事件，否则为滑动事件则不触发点击事件
                    // 当滑动时，让事件自身消费掉，不会触发点击事件
                    return@setOnTouchListener absX > 6 || absY > 6
                }
                else -> {

                }
            }
            false
        }

        mCircleView.setOnClickListener {
            Toast.makeText(mContext, "点击小球", Toast.LENGTH_SHORT).show()
            // 隐藏小球
            // 显示状态栏
            // 开启动画
        }
    }

    private fun getWindowWidth(): Int {
        val point = Point()
        mWindowManager.defaultDisplay.getSize(point)
        return point.x
    }

    fun showCircleView() {
        params.width = 150
        params.height = 150
        // 注意这里使用的是 or 并不是 and，使用and会与预期不一致
        params.gravity = Gravity.START or Gravity.TOP

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE
        }

        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE and
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL and
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
        params.format = PixelFormat.RGBA_8888

        mWindowManager.addView(mCircleView, params)
    }
}